﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DiskFileUpload
{
    public class UploadFiles : System.Collections.CollectionBase, System.IDisposable
    {
        public static readonly string DiskFileUpload_GUID = "DiskFileUpload_GUID";
        private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public string ApplicationKey{ get; set; }

        private int completePercent = 0;
        public int CompletePercent
        {
            get { return this.completePercent; }
        }

        public void CompletePercentHander( object sender, HttpWorkerFileUploadEventArgs e)
        {

            this.completePercent = (int)(e.Position * 100 / e.Length);

            this.logger.Trace("Percent: {0}",
                    this.completePercent
               );

         
        }

        public int Add(FileItem item)
        {
            return this.List.Add(item);
        }

        public void Insert(int index, FileItem value)
        {
            List.Insert(index, value);
        }

        public void Remove(FileItem value)
        {
            List.Remove(value);
        }


        public FileItem this[int index]
        {
            get
            {
                return ((FileItem)List[index]);
            }
            set
            {
                List[index] = value;
            }
        }

        public string ToContentString(string boundary)
        {
            boundary = "\r\n--" + boundary;
            System.Text.StringBuilder builder = new StringBuilder();
            builder.Append(boundary.Substring(2));

            foreach (FileItem item in this.List)
            {
                builder.Append(item.ToContentString(boundary));
            }

            builder.Append("--\r\n");
            return builder.ToString();
        }

        #region IDisposable Members

        public void Dispose()
        {
            foreach (FileItem item in this)
            {
                item.Dispose();
            }
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                HttpApplicationState application = context.Application;
                application.Remove(UploadFiles.DiskFileUpload_GUID);
            }
        }

        #endregion
    }
}
